package com.system.user.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

@Api(tags = "测试接口")
@RestController
@RequestMapping("/test")
public class TestController {

    @ApiOperation(value = "导出商品清单模板", notes = "导出商品清单模板", httpMethod = "POST")
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody Map<String, Object> test, HttpServletResponse response) {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:static/file/模板.docx");
        String fileName = "test.docx";
        String codedFileName = null;
        try {
            List<Map<String, Object>> maps = new ArrayList<>();
            for (int i = 1; i<= 15; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("xh", i);
                map.put("mc", "名称" + i);
                map.put("dj", i*10);
                map.put("dw", "个");
                map.put("ze", i*10);
                map.put("je", i*10 + i);
                maps.add(map);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("test", "某某公司");
            map.put("goodsList", maps);
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder().bind("goodsList", policy).build();
            XWPFTemplate doc = XWPFTemplate.compile(
                    "C:\\Users\\weimi\\Desktop\\模板.docx", config).render(map);
//            InputStream input = resource.getInputStream();
            codedFileName = URLEncoder.encode(fileName,"UTF-8");
            String tmpPath = "C:\\Users\\weimi\\Desktop\\test\\" + fileName;
//            FileOutputStream fos = new FileOutputStream(tmpPath);
//            doc.write(fos);
            response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName);
            response.setContentType("application/force-download");
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            doc.write(osOut);
            osOut.flush();
            osOut.close();
            doc.close();
//            fos.close();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        } finally {
        }

    }

    @ApiOperation(value = "打包zip", httpMethod = "GET")
    @GetMapping("packZip")
    public void packZip(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test.zip", "utf-8"));
        response.setContentType("application/octet-stream");
        OutputStream outputStream = response.getOutputStream();
        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(outputStream);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        List<String> list = new ArrayList<>();
        list.add("http://xz.holytax.com/pdf/d/TyMC8lxvpIOFj*A7MWzlseAkUHXBexnoZ0IxufOjUTafdYPwJ9MhorlDWSfQzp72%5EchHcjfjAeB/v2.0");
        list.add("http://xz.holytax.com/pdf/d/TyMC8lxvpIOFj*A7MWzlsZPzX6LYK6WcZ0IxufOjUTb7a1I1-KrzPrlDWSfQzp72%5EIFbabBbhE/v2.0");
        for (String s : list) {
            URL url = new URL(s);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(3*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            byte[] getData = readInputStream(inputStream);
            ArchiveEntry entry = new ZipArchiveEntry("test" + UUID.randomUUID() + ".pdf");
            zous.putArchiveEntry(entry);
            zous.write(getData);
            zous.closeArchiveEntry();
            inputStream.close();
        }
        zous.close();
//        URL url = new URL(list.get(0));
//        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//        conn.setRequestMethod("GET");
//        conn.setDoInput(true);
//        conn.setConnectTimeout(3*1000);
//        InputStream inputStream = conn.getInputStream();
//        byte[] bytes = readInputStream(inputStream);
//        //文件保存位置
//        File saveDir = new File("C:\\Users\\weimi\\Desktop\\test");
//        if(!saveDir.exists()){
//            saveDir.mkdir();
//        }
//        File file = new File(saveDir+File.separator+"test.pdf");
//        FileOutputStream fos = new FileOutputStream(file);
//        fos.write(bytes);
//        if(fos!=null){
//            fos.close();
//        }
//        OutputStream bos = response.getOutputStream();
//        while((inputStream.read(buffer)) != -1) {
//            bos.write(buffer);
//        }
//        bos.flush();
//        bos.close();
        outputStream.close();
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
        bos.close();
        return bos.toByteArray();

    }
}
